<?php

class AuthoritiesController extends AppController {

    var $name = "Authorities";
    var $uses = array('AviationAuthority');
    var $paginate = array(
        'AviationAuthority' => array(
            'limit' => 20,
            'order' => array('country', 'name')
        )
    );

    public function admin_add($id = NULL) {

        if (isset($id)) {
            $authority = $this->AviationAuthority->findById($id);
            $this->set('authority', $authority);
        }

        if ($this->RequestHandler->isAjax()) {
            if (isset($_POST['data'])) {
                $this->autoRender = false;

                $this->AviationAuthority->create($_POST['data']['AviationAuthority']);
                $data = $this->AviationAuthority->save();

                $data['AviationAuthority']['id'] = $this->AviationAuthority->id;

                echo json_encode($data);
            }
        }
    }

    public function admin_details() {

        if ($this->RequestHandler->isAjax()) {
            $authority_id = isset($_POST['authority_id']) ? $_POST['authority_id'] : -1;
            $this->set('authority', $this->AviationAuthority->read(null, $authority_id));
        }
    }

    /**
     * Returns basic contact information for display when filling the Request Form 
     */
    public function admin_contact_details() {
        $this->autoRender = false;
        
        if (isset($_GET['authority_id'])) {
            $authority = $this->AviationAuthority->find('first', array(
                'fields' => array('telephone', 'address', 'email'),
                'conditions' => array('AviationAuthority.id' => $_GET['authority_id']),
                'recursive' => -1)
            );
            
            echo json_encode($authority);
        }
    }

    /**
     * Deletes the AviationAuthority with the specified records from the system
     * 
     * @param int $id 
     */
    public function admin_delete($id) {
        $this->autoRender = false;
        $this->AviationAuthority->id = $id;
        $this->AviationAuthority->delete();
    }

    function admin_delete_selected() {

        if ($this->RequestHandler->isAjax()) {
            $this->autoRender = false;

            $this->AviationAuthority->deleteAll(array('AviationAuthority.id' => explode(",", $_POST['ids'])));
        }
    }

    function admin_list() {
        $authorities = $this->paginate('AviationAuthority', array(
            $_POST['term'] . " LIKE" => '%' . $_POST['field'] . "%"
        ));
        
        $this->set('authorities', $authorities);
    }
}

?>
